package com.unis.controller.tool;

import java.util.HashMap;
import java.util.List;

import com.unis.logger.TargetLogger;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.Map;

import com.unis.dto.ResultDto;
import com.unis.common.exception.http.RequestEntityTooLargeException;
import com.unis.common.excel.ExportBeanExcel;
import com.unis.common.util.ValidateUtil;

import com.unis.controller.BaseController;
import com.unis.model.tool.Sdh;
import com.unis.service.tool.SdhService;

/**
 * @author xuk
 * @version 1.0
 * @since 2019-04-25
 */
@Controller
@RequestMapping("/tool/sdh")
public class SdhController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(SdhController.class);

    @Autowired
    private SdhService sdhService;
    
    
    @RequestMapping("/page")
    public String forwordPage(String jtype, Model model)  {
        model.addAttribute("jtype",jtype);
        return "tool/sdh/sdhPage";
    }

    @TargetLogger("07020401")
    @RequiresPermissions("ROLE_VIEW")
    @RequestMapping( "/list")
    @ResponseBody
    public ResultDto querySdhList(@RequestParam Map<?, ?> paramMap){
    	int pageSize = paramMap.get("pageSize")==null ? 10 : Integer.parseInt(paramMap.get("pageSize").toString());
        int pageNumber = paramMap.get("pageNumber")==null ? 1 : Integer.parseInt(paramMap.get("pageNumber").toString());
        try {
            ResultDto page = sdhService.queryListByPage(paramMap,pageNumber,pageSize);
            return page;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new RequestEntityTooLargeException(e.getMessage());
        }
    }

    @TargetLogger("07020402")
    @RequiresPermissions("ROLE_VIEW")
    @RequestMapping("/excel")
    public void exportSdhList(HttpServletResponse response,@RequestParam Map<?, ?> paramMap){
        //导出默认1000行
        int pageSize = EXPORT_SIZE;
        int pageNumber = 1;
        OutputStream os = null;
        try {
            ResultDto page = sdhService.queryListByPage(paramMap,pageNumber,pageSize);
            List list = page.getRows();

            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Content-Disposition", "attachment;filename=exportSdh"+ System.currentTimeMillis() + ".xls");
            os = response.getOutputStream();

            ExportBeanExcel<Sdh> export = new ExportBeanExcel<Sdh>();
            //根据需求选择导出字段，注意数据库中带有_等字符字段修改
            //导出表头
            String[] headers = {"机构号","地区码","机构名称","录入时间"};
            //对应字段 headers 与cols一一对应
            String[] cols = {"jgh","dqm","dwmc","rksj"};
			
            export.exportExcel("sheet",headers,cols,list,os);

            os.flush();
            os.close();
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new RequestEntityTooLargeException(e.getMessage());
        }
    }

    @TargetLogger("070201")
    @RequiresPermissions("ROLE_CURD")
    @RequestMapping("/curd")
    @ResponseBody
    public Map<String,String> curd(String curdType,Sdh sdh) throws Exception {
    	Map<String,String> resultMap = new HashMap<>();
    	String msg = null;
        if (sdh!=null){
        	if (StringUtils.equalsIgnoreCase(curdType,"insert")){
        		//valid校验需在Sdh的字段上增加校验规则，规则与表单规则保持一致
        		msg = ValidateUtil.valid(sdh);
        		if (StringUtils.isNotBlank(msg)){
        			logger.error("valid insert Sdh is error :"+msg);
                     resultMap.put("msg",msg);
                     return resultMap;
                 }
                 sdhService.insert(sdh);
            }else if (StringUtils.equalsIgnoreCase(curdType,"delete")){
            	if(StringUtils.isNotBlank(sdh.getPk())) {
                    sdhService.delete(sdh.getPk()); //主键删除
                }else {
                    msg="没有要删除的数据";
                    logger.error("valid delete Sdh is error :"+msg);
                    resultMap.put("msg",msg);
                    return resultMap;
                }
            }else if (StringUtils.equalsIgnoreCase(curdType,"update")){
            	msg = ValidateUtil.valid(sdh);
        		if (StringUtils.isNotBlank(msg)){
        			 logger.error("valid update Sdh is error :"+msg);
                     resultMap.put("msg",msg);
                     return resultMap;
                 }
                sdhService.updateByPrimaryKey(sdh);
            }
            msg = "操作成功";
        }else{
            msg="信息未填写";
            logger.error(msg);
        }
    	resultMap.put("msg",msg);
        return resultMap;
    }
    
}
